IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cms_sp_TemplateSelectAll]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[cms_sp_TemplateSelectAll]
GO
CREATE procedure [dbo].[cms_sp_TemplateSelectAll]
(
@SiteGroupId int = null,
@SiteId int = null
)
as
select 
	Templates.TemplateId,
    Templates.SiteId,
    Templates.SiteGroupId,
    Templates.TemplateName,
	Templates.TemplateUrl,
	Templates.TemplateTypeKey,
	Templates.IsDefault,
	(select count(TemplateRegions.TemplateId) from dbo.TemplateRegions
		where TemplateRegions.TemplateId = Templates.TemplateId) as 'TemplateRegionsCount',
    Templates.CreatedBy,
    Templates.DateCreated,
    Templates.LastUpdatedBy,
    Templates.DateLastUpdated,
    Templates.DefaultRegionId
from dbo.Templates
where (Templates.SiteGroupId is null and Templates.SiteId is null) or 
	(Templates.SiteGroupId = @SiteGroupId and Templates.SiteId is null) or
	(Templates.SiteGroupId = @SiteGroupId and Templates.SiteId = @SiteId)


GO

